﻿using AspectInjector.Broker;
using MQ.Core.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MQ.Core.Cache
{
    [Aspect(Scope.Global)]
    public class CacheAspect
    {
        public string key { get; set; }
        public bool delete { get; set; }
        private ICache cache = CacheFactory.Redis();
        //public CacheAttribute() { }
        //public CacheAspect(string key, bool delete = false)
        //{
        //    this.key = key;
        //    this.delete = delete;
        //}
        [Advice(Kind.Around)]
        public object Handle([Argument(Source.ReturnType)]Type type, [Argument(Source.Target)]Func<object[], object> method, [Argument(Source.Arguments)] object[] arguments, [Argument(Source.Triggers)] Attribute[] triggers)

        {
            foreach(var trigger in triggers.OfType<CacheAttribute>())
            {
                key = trigger.Key;
                delete = trigger.Delete;
            }
            if (!delete)
            {
                var data = cache.Get<string>(key);
                if (data != null) return data.ToObject(type);
                else
                {
                    var result = method(arguments);
                    cache.Set(key, result);
                    return result;
                }
            }
            else
            {
                var result = method(arguments);
                cache.Remove(key);
                return result;
            }
        }
    }
}
